import 'package:flutter/cupertino.dart';

import 'package:flutter/material.dart';

class ScrollControllerTestRoute extends StatefulWidget {
  @override
  ScrollControllerTestRouteState createState() =>
      new ScrollControllerTestRouteState();
}

class ScrollControllerTestRouteState extends State<ScrollControllerTestRoute> {
  ScrollController _controller = new ScrollController();

  bool showToTopSpan = false; //是否显示“返回到”顶部按钮

  @override
  void initState() {
    _controller.addListener(() {
      print(_controller.offset); //打印滚动位置
      if (_controller.offset < 1000 && showToTopSpan) {
        setState(() {
          showToTopSpan = false;
        });
      } else if (_controller.offset >= 1000 && showToTopSpan == false) {
        setState(() {
          showToTopSpan = true;
        });
      }
    });
  }

  @override
  void dispose() {
    //为了避免内存泄漏，需要调用_controller.dispose
    _controller.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("滚动控制"),
      ),
      body: Scrollbar(
          child: ListView.builder(
              itemCount: 100,
              itemExtent: 50.0,
              controller: _controller,
              itemBuilder: (context, index) {
                return ListTile(title: Text("$index"));
              })),
      floatingActionButton: !showToTopSpan
          ? null
          : FloatingActionButton(
              child: Icon(Icons.arrow_upward),
              onPressed: () {
                _controller.animateTo(0,
                    duration: Duration(milliseconds: 200), curve: Curves.ease);
              }),
    );
  }
}
